package com.jy.api.wechat.handler;


import com.jy.api.service.WechatMemberService;
import com.jy.api.wechat.builder.TextBuilder;
import com.jy.api.wechat.service.BaseWxService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;


public abstract class SubscribeHandler extends AbstractHandler {


    @Autowired
    WechatMemberService wechatMemberService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        BaseWxService weixinService = (BaseWxService) wxMpService;

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = wechatMemberService.handleSpecial(wxMessage, weixinService);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error("登陆失败：{}", e.getMessage(), e);

            return new TextBuilder().build("登陆失败！", wxMessage, weixinService);
        }

    }


}
